<?php

namespace app\api\controller;

use think\Controller;
use app\api\model\Nav;
use app\api\model\Terms;
use app\api\model\Relationship;
use think\Response;
use think\Db;

class MenuController extends Controller
{
	public $Success = TRUE;
	public $Msg = "";
	public $Data = "";

	//早班车栏目
    public function index()
    {
		$data = Nav::all(['cid'=>2,'parentid'=>45]);
        $res_data = array();

        for ($i=0; $i < count($data); $i++) {
            $nav_name = $data[$i]['label'];
            $nav_id = $data[$i]['id'];
            $null_data =  ["url_id"=>$nav_id,"url_title"=>$nav_name, "post_title"=>"无数据"];
            //term_id
            $term_id = Terms::get(['name'=>$nav_name])->getData('term_id'); 
            //object_id与文章是绑定的
            $objects = Relationship::where('term_id',$term_id)->where('status',1)->limit(10)->order('object_id','desc')->column('object_id');   

            if (!empty($objects))
            {
                $now = date('Y-m-d H:i:s',time());
                $posts = Db::table('cmf_posts')->where('id','in',$objects)->where('post_modified','lt',$now)->limit(1)->order('post_modified','desc')->select();
                $res_data[$i] = $posts == [] ? $null_data : ["url_id"=>$nav_id, "url_title"=>$nav_name, "post_title"=>$posts[0]["post_title"]];
            } else {
                $res_data[$i] = $null_data;
            }
        }
        
        //获取栏目名称 
    	$this->Msg = "早班车栏目";
        return $this->response(['Success'=>true,'Msg'=>'','Data'=>$data, 'TopData'=>$res_data]);
    }
    
  protected function response($data, $type = 'json', $code = 200)
    {
        return Response::create($data, $type,200,['Access-Control-Allow-Origin'=>'*'])->code($code);
    }
    

}
